/*
 * marketsim-eclipsetrader
 *
 * Copyright (C) 2008-2011 Steve Phelps and John Cartlidge
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 */
package victria.marketsim.eclipsetrader.feed;

import java.util.HashSet;

import org.apache.log4j.Logger;

import victria.marketsim.core.BeanFactorySingleton;
import victria.marketsim.core.MarketService;

import net.sourceforge.eclipsetrader.core.ILevel2Feed;
import net.sourceforge.eclipsetrader.core.db.Security;

public abstract class AbstractFeed implements Runnable {

	protected HashSet<Security> securities;

	protected boolean stopping = false;
	
	protected long pollInterval = 1000;
	
	protected MarketService marketService;
	
	static Logger logger = Logger.getLogger(AbstractFeed.class);
	
	public AbstractFeed() {
		securities = new HashSet<Security>();
		marketService = (MarketService) BeanFactorySingleton
				.getBean("rmiMarketService");
		logger.debug("marketService = " + marketService);
	}

	public void start() {
		logger.debug("Starting feed: " + this);
		stopping = false;
		new Thread(this).start();
	}

	public void stop() {
		logger.debug("Stopping feed");
		stopping = true;		
	}
	
	public void run() {
		while (!stopping) {
			
			// Sleep for 1 second (1000 ms)
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
			
			// Refresh the book
			refresh();
		}
	}
	
	public void subscribe(Security security) {
		logger.debug("Subscribing to " + security);
		securities.add(security);
	}

	public void unSubscribe(Security security) {
		logger.debug("Unsubscribing from " + security); 
		securities.remove(security);
	}
	
	public abstract void refresh();
}